"""
2020-07-26
更新如下：
1. 修正了计算输出文件数量总数的错误；
2. 优化屏幕显示内容
"""

import numpy as np
import os
import tkinter as tk
from tkinter import filedialog
import time

# reset the original temperature field
# adding steps information

print('请选择ntl数据')
time.sleep(0.5)
root = tk.Tk()
root.withdraw()
fullPath = filedialog.askopenfilename()
cwd = os.path.split(fullPath)[0]
file = os.path.split(fullPath)[1]
filename = file[0:-4]
if len(filename) == 0:
    print('未选择数据，退出程序中...')
    time.sleep(2)
    raise SystemExit(0)
else:
    print('读取文件{}成功！'.format(filename))
time.sleep(1)


# Creating own range function
def myRange(start, end, step):
    i = start
    while i < end:
        yield i
        i += step
    yield end


print('是否需要重新指定输出文件夹？默认数据保存在输入文件夹中新建的''nodalTemp''文件夹中')
createDirectFlag = input('请输入(y/n)，默认为n: ') or 'n'
if createDirectFlag in ('y', 'Y'):
    print('请选择输出文件夹')
    time.sleep(0.5)
    root = tk.Tk()
    root.withdraw()
    outd = filedialog.askdirectory()
elif createDirectFlag in ('n', 'N'):
    outd = os.path.join(cwd, 'nodalTemp')
    if os.path.isdir(os.path.join(cwd, 'nodalTemp')):
        pass
    else:
        os.makedirs(outd)
else:
    print('输入错误，将数据保存至默认文件夹中')
    outd = os.path.join(cwd, 'nodalTemp')
    if os.path.isdir(os.path.join(cwd, 'nodalTemp')):
        pass
    else:
        os.makedirs(outd)

if len(outd) == 0:
    print('未选择输出文件夹，退出程序...')
    time.sleep(2)
    raise SystemExit(0)
else:
    pass
with open(fullPath, 'r') as f:  # OPEN INPUT FILE
    f = f.read().split()
    indexes = [0, 1, 2, 8]
    for index in sorted(indexes, reverse=True):
        del f[index]
    inputF = map(float, f)
    inputF = ['%e' % (x) for x in inputF]
    totalNodeNumber = int(float(inputF[0]))
    totalStepNumber = int(float(inputF[4]))
    arrInput = np.array(inputF[5:]).astype(float)
    # 将输入数组变化形状，变化后为 n*m，n为节点数，m为分析步数+1，第一列为节点标签
    arrInputShaped = arrInput.reshape(totalNodeNumber, totalStepNumber + 1)
    print('共有{}个分析步数据点'.format(totalStepNumber))
    incNum = int(input('请输入输出数据点间隔，默认为1：')) or 1
    if totalStepNumber % incNum == 0:
        totalFileCount = int((totalStepNumber - totalStepNumber % incNum) / incNum)
    else:
        totalFileCount = int((totalStepNumber - totalStepNumber % incNum) / incNum + 1)
    includeLastStepFlag = input('输出是否包含最后一步(y/n)，默认为y：') or 'y'
    print('******************************')
    print('正在创建节点温度文件...')
    if includeLastStepFlag in ('n', 'N'):
        for i in range(1, totalStepNumber + 1, incNum):
            np.savetxt(os.path.join(outd, 'nodalTempStep%d.inc') % (i - 1), arrInputShaped[:, [0, i]],
                       fmt='%i' + ', %1.6f')
            print('{}/{}个节点温度文件已创建'.format(int((i - i % incNum) / incNum + 1), totalFileCount))
    else:
        for i in myRange(1, totalStepNumber, incNum):
            np.savetxt(os.path.join(outd, 'nodalTempStep%d.inc') % (i - 1), arrInputShaped[:, [0, i]],
                       fmt='%i' + ', %1.6f')
            if totalStepNumber % incNum == 0:
                print('{}/{}个节点温度文件已创建'.format(int((i - i % incNum) / incNum) + 1, totalFileCount + 1))
            else:
                print('{}/{}个节点温度文件已创建'.format(int((i - i % incNum) / incNum) + 1, totalFileCount))

print('创建节点温度文件成功！')
time.sleep(0.5)
print('******************************')
print('正在创建ABAQUS输入文件...')
with open(os.path.join(outd, '%s_steps.inp') % filename, 'w') as f:
    if includeLastStepFlag in ('n', 'N'):
        for i in range(0, totalStepNumber, incNum):
            print('**', file=f)
            print('** STEP: Step-%d' % i, file=f)
            print('**', file=f)
            print('*Step, name=Step-%d, nlgeom=yes' % i, file=f)
            print('*Static', file=f)
            print('0.001, 1., 1e-10, 0.2', file=f)
            print('*Temperature', file=f)
            print('*Include, Input=nodalTempStep%d.inc' % i, file=f)
            print('** ', file=f)
            print('** OUTPUT REQUESTS', file=f)
            print('** ', file=f)
            print('*Restart, write, frequency=0', file=f)
            print('** ', file=f)
            print('** FIELD OUTPUT: F-Output-1', file=f)
            print('** ', file=f)
            print('*Output, field', file=f)
            print('*Node Output', file=f)
            print('CF, NT, RF, U', file=f)
            print('*Element Output, directions=YES', file=f)
            print('E, EE, IE, LE, MISES, NE, PE, PEEQ, PEMAG, S, THE', file=f)
            print('** ', file=f)
            print('** HISTORY OUTPUT: H-Output-1', file=f)
            print('*Output, history, variable=PRESELECT', file=f)
            print('*End Step', file=f)
    else:
        for i in myRange(0, totalStepNumber - 1, incNum):
            print('**', file=f)
            print('** STEP: Step-%d' % i, file=f)
            print('**', file=f)
            print('*Step, name=Step-%d, nlgeom=yes' % i, file=f)
            print('*Static', file=f)
            print('0.001, 1., 1e-10, 0.2', file=f)
            print('*Temperature', file=f)
            print('*Include, Input=nodalTempStep%d.inc' % i, file=f)
            print('** ', file=f)
            print('** OUTPUT REQUESTS', file=f)
            print('** ', file=f)
            print('*Restart, write, frequency=0', file=f)
            print('** ', file=f)
            print('** FIELD OUTPUT: F-Output-1', file=f)
            print('** ', file=f)
            print('*Output, field', file=f)
            print('*Node Output', file=f)
            print('CF, NT, RF, U', file=f)
            print('*Element Output, directions=YES', file=f)
            print('E, EE, IE, LE, MISES, NE, PE, PEEQ, PEMAG, S, THE', file=f)
            print('** ', file=f)
            print('** HISTORY OUTPUT: H-Output-1', file=f)
            print('*Output, history, variable=PRESELECT', file=f)
            print('*End Step', file=f)
print('创建ABAQUS输入文件成功！')
print('******************************')
time.sleep(0.5)
exitFlag = input("按任意键退出程序...")
